<template>
  <el-form
    ref="ruleFormRef"
    :model="data.staffInfo"
    :label-width="formLabelWidth"
    size="large"
    :rules="rules"
  >
    <el-row>
      <el-col :span="12">
        <el-form-item label="RFID卡号" prop="staff_rfid">
          <el-input
            clearable
            v-model="data.staffInfo.staff_rfid"
            style="width: 16rem"
          /> </el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item label="员工工号" prop="staff_number">
          <el-input
            clearable
            disabled
            v-model.number="data.staffInfo.staff_number"
            style="width: 16rem"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="员工姓名" prop="staff_name">
          <el-input
            clearable
            v-model="data.staffInfo.staff_name"
            style="width: 16rem"
          /> </el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item label="身份证号" prop="staff_id">
          <el-input
            clearable
            v-model="data.staffInfo.staff_id"
            style="width: 16rem"
          /> </el-form-item
      ></el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="密码" prop="staff_password">
          <el-input
            clearable
            v-model="data.staffInfo.staff_password"
            show-password
            style="width: 16rem"
          /> </el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item label="年龄" prop="staff_age">
          <el-input
            clearable
            v-model.number="data.staffInfo.staff_age"
            autocomplete="off"
            style="width: 16rem"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="在职状态" prop="staff_state">
          <el-select
            clearable
            v-model="data.staffInfo.staff_state"
            placeholder="请选择"
            size="large"
            style="width: 16rem"
          >
            <el-option key="1" label="在岗" value="1" />
            <el-option key="2" label="休息" value="2" />
            <el-option
              key="3"
              label="离职"
              value="3"
            /> </el-select></el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item label="电话号码" prop="staff_phone">
          <el-input v-model="data.staffInfo.staff_phone" style="width: 16rem" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="操作等级" prop="staff_level">
          <el-select
            clearable
            v-model="data.staffInfo.staff_level"
            placeholder="请选择"
            size="large"
            style="width: 16rem"
          >
            <el-option key="1" label="1" :value="1" />
            <el-option key="99" label="99" :value="99" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" @click.stop>
        <el-form-item label="入职日期" prop="staff_date">
          <el-date-picker
            clearable
            v-model="data.staffInfo.staff_date"
            type="datetime"
            placeholder="请选择"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="性别" prop="staff_sex">
          <el-radio-group v-model="data.staffInfo.staff_sex">
            <el-radio label="1" size="large">男</el-radio>
            <el-radio label="0" size="large">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="sub_button">
          <el-button
            type="primary"
            style="width: 16rem"
            v-if="addOrMod"
            @click="addStaff(ruleFormRef)"
            >添加</el-button
          >
          <div v-else>
            <el-button
              type="primary"
              style="width: 8rem"
              @click="submit(ruleFormRef)"
              >确定</el-button
            >
            <el-button type="primary" style="width: 8rem" @click="cancel"
              >取消</el-button
            >
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <el-form-item label="上传照片" prop="staff_photo">
          <el-upload
            class="avatar-uploader"
            action="/api/common/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"
              ><Plus
            /></el-icon> </el-upload></el-form-item
      ></el-col>
    </el-row>
  </el-form>
</template>

<script setup>
import { reactive, ref, watch, computed, defineProps } from 'vue'
import { useStore } from 'vuex'
import { reqInsertStaff, reqUpdateStaff } from '@/api/staff'
import { ElMessage } from 'element-plus'
const formLabelWidth = '8rem'
const props = defineProps({
  changeV: {
    required: false
  }
})
const ruleFormRef = ref()
const data = reactive({
  staffInfo: {
    staff_rfid: null,
    staff_number: null,
    staff_name: null,
    staff_id: null,
    staff_password: null,
    staff_age: null,
    staff_state: null,
    staff_date: null,
    staff_level: null,
    staff_photo: null,
    staff_phone: null,
    staff_sex: null
  },
  rules: {
    staff_rfid: [
      { required: true, message: 'RFID卡号不能为空', trigger: 'blur' },
      { min: 3, max: 20, message: '长度必须是3-20', trigger: 'blur' }
    ],
    staff_number: [
      { required: true, message: '员工工号不能为空', trigger: 'blur' }
    ],
    staff_name: [
      { required: true, message: '员工姓名不能为空', trigger: 'blur' }
    ],
    staff_id: [
      { required: true, message: '身份证号不能为空', trigger: 'blur' }
    ],
    staff_password: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      { min: 6, message: '长度最短6位', trigger: 'blur' }
    ],
    staff_age: [
      { required: true, message: '年龄不能为空', trigger: 'blur' },
      { type: 'number', message: '年龄必须是数字' }
    ],
    staff_state: [
      { required: true, message: '在职状态不能为空', trigger: 'change' }
    ],
    staff_date: [
      { required: true, message: '入职日期不能为空', trigger: 'change' }
    ],
    staff_level: [
      { required: true, message: '操作等级不能为空', trigger: 'change' }
    ],
    staff_photo: [
      { required: true, message: '照片不能为空', trigger: 'change' }
    ],
    staff_phone: [
      { required: true, message: '电话号码不能为空', trigger: 'blur' }
    ],
    staff_sex: [{ required: true, message: '性别不能为空', trigger: 'change' }]
  }
})
const { staffInfo, rules } = data
const store = useStore()
const { dispatch, getters } = store
const imageUrl = ref('')

// 添加按钮
const addStaff = (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      const result = await reqInsertStaff([data.staffInfo])
      if (result.code === 200) {
        ElMessage({
          message: result.msg,
          type: 'success'
        })
        getStaffList()
      } else {
        ElMessage({
          message: result.msg,
          type: 'warning'
        })
      }
    } else {
      return false
    }
  })
}
// 提交按钮
const submit = (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      const result = await reqUpdateStaff(data.staffInfo)
      if (result.code === 200 && result.data === 1) {
        ElMessage({
          message: result.msg,
          type: 'success'
        })
        getStaffList()
      } else {
        ElMessage({
          message: result.msg,
          type: 'warning'
        })
      }
      props.changeV()
    } else {
      return false
    }
  })
}
// 取消按钮
const cancel = () => {
  props.changeV()
}
// 获取员工列表
const getStaffList = () => {
  dispatch('staff/getStaffList', { pagination })
}
// 文件上传成功的钩子
const handleAvatarSuccess = (response, uploadFile) => {
  // 将返回的图片名称保存
  data.staffInfo.staff_photo = response.data
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
}
// 文件上传前的钩子
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片必须是JPG格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过2MB!')
    return false
  }
  return true
}

const staff = computed(() => getters.staff)
const addOrMod = computed(() => getters.addOrMod)
const pagination = computed(() => getters.pagination)
const newNumber = computed(() => getters.staff_newNumber)

watch(
  newNumber,
  (newValue, oldValue) => {
    if (newValue !== undefined && addOrMod.value) {
      imageUrl.value = ''
      for (const key in staffInfo) {
        if (key !== 'staff_number') {
          staffInfo[key] = null
        }
      }
      staffInfo.staff_number = newNumber
    }
  },
  { immediate: true }
)
watch(
  staff,
  (newValue, oldValue) => {
    if (newValue !== [] && !addOrMod.value) {
      if (staff.value.staff_photo) {
        imageUrl.value = `/api/common/download?name=${staff.value.staff_photo}`
      }
      data.staffInfo = newValue
    }
  },
  { immediate: true }
)
</script>

<style lang="scss" scoped>
.sub_button {
  display: flex;
  justify-content: right;
  margin-right: 2rem;
  margin-top: 2rem;
}

.avatar-uploader .avatar {
  width: 8rem;
  height: 8rem;
  display: block;
}
</style>
